def clean(self): if self.tipo_dato_contacto == 'EMAIL': try: validate_email(self.dato_contacto_valor) email_valido = True except ValidationError: email_valido = False if not email_valido: raise ValidationError( {'dato_contacto_valor': _('Email inválido')}) if self.tipo_dato_contacto == 'TEL_CEL': try: validate_integer(self.dato_contacto_valor) numero_valido = True except ValidationError: numero_valido = False if not numero_valido or len(str(self.dato_contacto_valor)) < 8: raise ValidationError({ 'dato_contacto_valor': _('Número inválido. Ingrese el número sin guiones ni espacios.' ) })
def input_validator(user_data): try: validate_email(user_data['email']) validate_integer(user_data['phone_number']) if not user_data['name'].isalpha(): return JsonResponse({"error": "INVALID_NAME"}, status=400) user_data['nickname'].encode(encoding='ascii') if not (user_data['nickname'].isalpha() and user_data['nickname'].islower()): return JsonResponse({"error": "INVALID_NICKNAME"}, status=400) if not re.match( r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_])[A-Za-z\d!@#$%^&*()_]{10,}', user_data['password']): return JsonResponse({"error": "INVALID_PASSWORD"}, status=400) except UnicodeEncodeError: return JsonResponse({"error": "INVALID_NICKNAME"}, status=400) except ValidationError: return JsonResponse({"error": "INVALID_TYPE"}, status=400) except KeyError: return JsonResponse({"error": "INVALID_KEYS"}, status=400)
def clean_previous_reference3_contact_number(self): data = self.cleaned_data['previous_reference3_contact_number'] if data != '': try: validate_integer(data) except ValidationError: raise forms.ValidationError('Enter a valid phone number') return data
def long_to_ip(value): validators.validate_integer(value) value = int(value) validators.MinValueValidator(0)(value) validators.MaxValueValidator(4294967295)(value) return "%d.%d.%d.%d" % (value >> 24, value >> 16 & 255, value >> 8 & 255, value & 255)
def clean_phone_number(self): data = self.cleaned_data['phone_number'] if data != '': try: validate_integer(data) except ValidationError: raise forms.ValidationError('Enter a valid phone number') return data
def clean_project(self): pid = self.cleaned_data['project'] validate_integer(pid) if ActiveProject.objects.get( id=pid) not in ActiveProject.objects.filter( submission_status=10): raise forms.ValidationError('Incorrect project selected.') return pid
def clean(self): cd = self.cleaned_data if (validate_integer(cd.get('id')) == False): raise ValidationError(u'Numbers only please.') if (validate_integer(cd.get('birthdate')) == False): raise ValidationError(u'Numbers only please.') return cd
def long_to_ip(value): validators.validate_integer(value) value = long(value) validators.MinValueValidator(0)(value) validators.MaxValueValidator(4294967295)(value) return '%d.%d.%d.%d' % (value >> 24, value >> 16 & 255, value >> 8 & 255, value & 255)
def validate_freeswitch_integer(value): try: validate_integer(value) except ValidationError, e: try: validate_freeswitch_variable(smart_unicode(value)) except ValidationError: raise ValidationError(_(u'Enter an integer or a ' 'FreeSWITCH variable.'))
def clean_phone_number(self): phone_number = self.cleaned_data.get("phone_number") try: validators.validate_integer(phone_number) valid_phone_number = True except: raise forms.ValidationError("Not a valid phone number, 0-9 only!.") valid_phone_number = False if valid_phone_number: return phone_number
def edit(request, upload_num): photos = Photo.objects.filter(from_user=request.user, msg_flag=False, upload_num=upload_num) info_list = [] for photo in photos: print(photo.info) if photo.info is not None: info = photo.info if request.method == "POST": period = request.POST.get('period') try: validate_integer(period) except: print("error") msg = '기간은 숫자로만 입력해야합니다.' context = {'msg': msg} return render(request, 'main_page/message.html', context) from_name = request.POST.get('from') random_day = random.choice(range(0, int(period) + 1)) now = datetime.now() td = timedelta(days=random_day, minutes=0) random_date = now + td phone_to = request.POST.get('phone_to') try: validate_integer(phone_to) except: msg = '핸드폰은 숫자로만 입력해야합니다.' context = {'msg': msg} return render(request, 'main_page/message.html', context) if len(phone_to) < 11: msg = '핸드폰 번호를 11자 입력해주세요.' context = {'msg': msg} return render(request, 'main_page/message.html', context) to_name = request.POST.get('to_name') message = request.POST.get('message') if len(message) > 40: msg = '메시지를 40자 이내로 입력해주세요' context = {'msg': msg} return render(request, 'main_page/message.html', context) info.period = period info.phone_to = phone_to info.to_name = to_name info.message = message info.send_date = random_date info.save() return redirect('main:confirm', upload_num) context = {'info': info} return render(request, 'main_page/edit.html', context)
def clean_phone(self): phone = self.data.get("phone") errors = dict() valid_phone = False try: validators.validate_integer(phone) valid_phone_number = True except: # raise forms.ValidationError("Not a valid phone number. 0-9 only") # valid_phone_number = False errors['phone'] = "Not a valid phone number. 0-9 only" return errors if valid_phone_number: return phone
def clean_value(self): rtype = self.cleaned_data["type"] value = self.cleaned_data["value"] if rtype == 'A': ip_version_validator(value, 4, "Need valid IPv4 Address for A record") elif rtype == 'AAAA': ip_version_validator(value, 6, "Need valid IPv6 Address for AAAA record") elif rtype == 'MX': values = value.split() if len(values) != 2: raise forms.ValidationError("Need priority and FQDN for MX record") prio, fqdn = values validate_integer(prio) full_domain_validator(fqdn) return value
def val_body(param, schema_body=None): if isinstance(param, dict): for schema_key, scheme_value in schema_body.items(): # if isinstance(schema_body[0], dict-study): for param_key, param_value in param.items(): if schema_key == param_key: if isinstance(param_value, str): RegexValidator(scheme_value, message="参数%s的值不合法" % param_key).__call__(param_value) elif isinstance(param_value, int): validate_integer(param_value) elif isinstance(param_value, list): val_xx(scheme_value, param_value) elif isinstance(param_value, dict): val_body(param_value, schema_body=scheme_value)
def ip_to_long(value): validators.validate_ipv4_address(value) lower_validator = validators.MinValueValidator(0) upper_validator = validators.MinValueValidator(255) value = value.split('.') output = 0 for i in range(0, 4): validators.validate_integer(value[i]) lower_validator(value[i]) upper_validator(value[i]) output += long(value[i]) * (256**(3 - i)) return output
def ip_to_long(value): validators.validate_ipv4_address(value) lower_validator = validators.MinValueValidator(0) upper_validator = validators.MinValueValidator(255) value = value.split('.') output = 0 for i in range(0, 4): validators.validate_integer(value[i]) lower_validator(value[i]) upper_validator(value[i]) output += long(value[i]) * (256**(3-i)) return output
def ip_to_int(value): validators.validate_ipv4_address(value) lower_validator = validators.MinValueValidator(0) upper_validator = validators.MaxValueValidator(255) value = [int(octet) for octet in value.split('.')] output = 0 for i in range(0, 4): validators.validate_integer(value[i]) lower_validator(value[i]) upper_validator(value[i]) output += value[i] * (256**(3-i)) return output
def clean_card_number(self, *args, **kwargs): card_number = self.cleaned_data.get("card_number") if validate_integer(card_number): raise forms.ValidationError( "This is not a valid credit card number") if len(card_number) != 16: raise forms.ValidationError( "This is not a valid credit card number") return card_number
def clean_value(self): name = self.cleaned_data['name'] value = self.cleaned_data['value'] now = timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE)) existing_setting = models.Setting.objects.filter(name=name, time_set__lte=now).latest('time_set') value_type = existing_setting.value_type # validate based on value_type if value_type == 'int': validators.validate_integer(value) elif value_type == 'string': try: str(value) except: raise exceptions.ValidationError(('Please enter a valid string.'), code='invalid') elif value_type == 'float': try: float(value) except: raise exceptions.ValidationError(('Please enter a valid float.'), code='invalid') elif value_type == 'email': validators.validate_email(value) elif value_type == 'bool': try: if int(value) not in [0, 1]: raise exceptions.ValidationError(('Please enter either 0 or 1.'), code='invalid') except: raise exceptions.ValidationError(('Please enter either 0 or 1.'), code='invalid') validators.validate_integer(value) elif value_type == 'semester_or_none': try: value = str(value.lower().strip(' ')) if value not in ['spring', 'fall', 'both', 'never']: raise exceptions.ValidationError(('Please enter either fall, spring, both, or never.'), code='invalid') else: return value except: raise exceptions.ValidationError(('Please enter either fall, spring, both, or never.'), code='invalid') return self.cleaned_data['value']
def set_pressure_target(request): if request.user.is_authenticated and request.method == "POST": if request.user.groups.filter(name="admin").exists(): imei = request.POST.get("imei", '') pressure_target = request.POST.get("pressure_target", '') command_queue = Command.objects.filter(imei=imei) if command_queue.count() >= 1: return HttpResponse( 'There already is a command being executed for this installation.' ) try: validate_integer(pressure_target) c = Command( imei=imei, command_string=f"SET_PRESSURE_TARGET: {pressure_target}") c.save() return HttpResponse('success') except ValidationError: return HttpResponse( 'There is already a command pending for the device') else: return HttpResponse('Insufficient permissions')
def set_phone_number(request, upload_num): photos = Photo.objects.filter(from_user=request.user, msg_flag=False, upload_num=upload_num) print(photos) if request.method == "POST": period = request.POST.get('period') try: validate_integer(period) except: print("error") msg = '기간은 숫자로만 입력해야합니다.' context = {'msg': msg, 'upload_num': upload_num} return render(request, 'main_page/message.html', context) phone_from = request.POST.get('phone_from') random_day = random.choice(range(0, int(period) + 1)) now = datetime.now() td = timedelta(days=random_day, minutes=0) random_date = now + td print( f'now: {now}, random_day={random_day}, random_date={random_date}') print(random_date) from_name = request.POST.get('from_name') phone_to = request.POST.get('phone_to') try: validate_integer(phone_to) except: msg = '핸드폰은 숫자로만 입력해야합니다.' context = {'msg': msg, 'upload_num': upload_num} return render(request, 'main_page/message.html', context) if len(phone_to) < 11: msg = '핸드폰 번호를 11자 입력해주세요.' context = {'msg': msg, 'upload_num': upload_num} return render(request, 'main_page/message.html', context) to_name = request.POST.get('to_name') message = request.POST.get('message') if len(message) > 40: msg = '메시지를 40자 이내로 입력해주세요.' context = {'msg': msg, 'upload_num': upload_num} return render(request, 'main_page/message.html', context) photo_info = Photo_info(send_date=random_date, phone_from=phone_from, phone_to=phone_to, from_name=from_name, to_name=to_name, message=message, period=period) photo_info.save() photos = Photo.objects.filter(from_user=request.user, msg_flag=False, upload_num=upload_num) print(f'photos: {len(photos)}') rd = random.choice(range(0, len(photos))) photos[rd].info = photo_info photos[rd].save() photo_info.link = f"https://palette-serendipity.herokuapp.com/main/photo/{photos[rd].pk}/{photos[rd].random_url}" photo_info.save() return redirect('main:confirm', upload_num) return render(request, 'main_page/set_phone_number.html')
def __call__(self, attrs): value = attrs[self.field] validate_integer(value)
def validate( self, value ): super( IntegerEmptyStringField, self ).validate( value ) if value: validate_integer( value )
def validate(self, value): # valueをバリデーションする super().validate(value) for id_ in value: validate_integer(id_)
def validate_fields(value): if (validate_integer(value) == False): raise forms.ValidationError('Numbers only please.') return value
def validate_age(self, value): validate_integer(value) if value < 1: raise serializers.ValidationError( "Negative value is not accepted.") return value
def clean(self): cd=self.cleaned_data validate_integer(cd.get('rut', None))
def validate_page_number(value): validate_integer(value)