我正在使用表单请求验证方法来验证laravel 5中的请求.我想用表单请求验证方法添加我自己的验证规则.我的请求类在下面给出.我想添加自定义验证numeric_array和字段项.
protected $rules = [
'shipping_country' => ['max:60'],
'items' => ['array|numericarray']
];
Run Code Online (Sandbox Code Playgroud)
我的cusotom功能如下
Validator::extend('numericarray', function($attribute, $value, $parameters) {
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
Run Code Online (Sandbox Code Playgroud)
如何在laravel5中使用此验证方法进行表单请求验证?
我来找你谈论角材料的问题.事实上,我认为这是一个问题,但我更喜欢先找一个误解.
关于我的问题的第一件事是上下文,我尝试做一个包含两个输入的简单表单:密码及其'确认.
用户form.component.ts
this.newUserForm = this.fb.group({
type: ['', Validators.required],
firstname: ['', Validators.required],
lastname: ['', Validators.required],
login: ['', Validators.required],
matchingPasswordsForm: this.fb.group(
{
password1: ['', Validators.required],
password2: ['', Validators.required],
},
{
validator: MatchingPasswordValidator.validate,
},
),
mail: ['', [Validators.required, Validators.pattern(EMAIL_PATTERN)]],
cbaNumber: [
'411000000',
[Validators.required, Validators.pattern(CBANUMBER_PATTERN)],
],
phone: ['', [Validators.required, Validators.pattern(PHONE_PATTERN)]],
}
Run Code Online (Sandbox Code Playgroud)
我的兴趣是匹配PasswordsForm FormGroup.你可以在上面看到验证器.
验证器在这里:
匹配-password.validator.ts
export class MatchingPasswordValidator {
constructor() {}
static validate(c: FormGroup): ValidationErrors | null {
if (c.get('password2').value !== c.get('password1').value) {
return { matchingPassword: true};
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
和HTML. …
我有一个"AllowedValuesValidator.java"类:
public class AllowedValuesValidator implements ConstraintValidator<AllowedValues, String> {
String[] values;
String defaultValue;
@Override
public void initialize(AllowedValues constraintAnnotation) {
values = constraintAnnotation.allowedValues();
defaultValue = constraintAnnotation.defaultValue();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (!StringUtils.isEmpty(defaultValue) && StringUtils.isEmpty(value)) {
value = defaultValue;
}
if (!StringUtils.isEmpty(value) && !Arrays.asList(values).contains(value)) {
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
和相应的接口类:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AllowedValuesValidator.class)
public @interface AllowedValues {
String message();
String fieldName();
int fieldNumber();
String[] allowedValues() default {"Y", "N"};
String defaultValue() default "";
} …Run Code Online (Sandbox Code Playgroud) 我试图实现自定义验证器.非异步one(cannotContainSpaces)工作得很好.async one(shouldBeUnique),是的,目前是微不足道的,应该按照我的理解返回promise,Validator对象应该解析.它没有.formControl上的错误集合在username控制台中显示:
{__zone_symbol__state: null, __zone_symbol__value: Array(0)}
Run Code Online (Sandbox Code Playgroud)
表单组件:
import { CustomValidators } from './custom.validators';
import { Component, Input } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'signup-form',
templateUrl: './signup-form.component.html',
styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {
form = new FormGroup({
username: new FormControl('', [
CustomValidators.cannotContainSpaces,
CustomValidators.shouldBeUnique
// Validators.email,
]),
password: new FormControl('', Validators.required)
})
get username() {
return this.form.get('username');
}
keyPressed(){
console.log(this.username.errors)
}
}
Run Code Online (Sandbox Code Playgroud)
自定义验证方法:
import { AbstractControl, ValidationErrors } …Run Code Online (Sandbox Code Playgroud) 我有一个自定义的模型驱动表单验证器来验证最大文本长度
export function maxTextLength(length: string) {
return function (control: FormControl) {
const maxLenghtAllowed: number = +length;
let value: string = control.value;
if (value !== '' && value != null) {
value = value.trim();
}
if (value != null && value.length > maxLenghtAllowed) {
return { maxTextLength: true };
}else {
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何编写单元测试用例形成这个?
unit-testing custom-validators karma-jasmine angular angular-reactive-forms
我有以下几片asp:
<asp:ValidationSummary ID="RegisterUserValidationSummary" runat="server" CssClass="failureNotification"
ValidationGroup="RegisterUserValidationGroup"/>
Run Code Online (Sandbox Code Playgroud)
...
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserNameTB">Username:</asp:Label>
<asp:TextBox ID="UserNameTB" runat="server" CssClass="textEntry"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="UserNameTB"
ValidationExpression="[a-zA-Z]{3,8}" ErrorMessage="Username must be between 3 to 8 chars" runat="server"
CssClass="failureNotification" ToolTip="Username must be between 3 to 8 chars" ValidationGroup="RegisterUserValidationGroup">
*</asp:RegularExpressionValidator>
<asp:CustomValidator ID="NoUserValidator" ControlToValidate="UsernameTB" runat="server" ErrorMessage="User Taken!" CssClass="failureNotification"
ValidationGroup="RegisterUserValidationGroup" OnServerValidate="UserValidate">*</asp:CustomValidator>
Run Code Online (Sandbox Code Playgroud)
然后功能:
protected void UserValidate(object source, ServerValidateEventArgs args)
{
SqlDataSource1.SelectCommand = "SELECT ClientID FROM [Clients] WHERE Username= '" + UserNameTB.Text + "'";
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
if (dv.Table.Rows.Count != 0)
args.IsValid = false; …Run Code Online (Sandbox Code Playgroud) 从文档http://1000hz.github.io/bootstrap-validator/:
添加要运行的自定义验证程序.验证器应该是接收jQuery元素作为参数的函数,并根据输入的有效性返回truthy或falsy值.
对象结构是:
{foo: function($el) { return true || false } }将验证器添加到输入中就像其他人一样
data-foo="bar".您还必须通过errors选项为任何自定义验证器添加默认错误消息.
我不太明白如何定义我自己的自定义验证器以及如何将它与此插件一起使用.
谁能给我一个简单的例子或提示?
我正在使用boost program_options 1.50.0
我想为我的程序foobar提供以下内容
foobar --debug 2 --debug 3
从boost program_options代码中,有一个示例regex.cpp,它显示了创建新类型并为该类型创建验证器.
我试过了,但它确实有效,但现在我不能使用其他一些add_options()typed_value选项,比如default_value,composing等.
这是我到目前为止尝试的内容:
#include <boost/program_options.hpp>
using namespace boost;
using namespace boost::program_options;
#include <iostream>
using namespace std;
struct lastmultioccurrenceint {
public:
lastmultioccurrenceint(int n) : n(n) {}
int n;
};
void validate(boost::any& v,
const std::vector< std::string >& xs,
//const std::vector< std::basic_string<charT> >& xs,
lastmultioccurrenceint* , int)
{
using namespace boost::program_options;
cerr << "IN VALIDATE" << endl;
//validators::check_first_occurrence(v);
string s = validators::get_single_string(xs);
if (!v.empty()) {
cerr << "\tPRINTTING MULTIOCCURENCE WARNING, allowing v to …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个自定义Angular 2表单Validator来检查数据库上是否存在用户.
这是我自定义表单的代码 Validator
import { FormControl } from '@angular/forms';
import {API} from "../services/api";
import {ReflectiveInjector} from "@angular/core";
export class EmailValidator {
constructor() {}
static checkEmail(control: FormControl,): any {
let injector = ReflectiveInjector.resolveAndCreate([API]);
let api = injector.get(API);
return api.checkUser(control.value).then(response => {
response;
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的自定义服务,它负责向后端的节点api发出请求
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class API {
private backendUrl = 'http://127.0.0.1:5000/api/register/';
constructor(private http: Http) { }
checkUser(email:string): Promise<any> {
return …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用自定义验证来验证表单.出于某种原因,我必须构建一个可以更改电子邮件或设置新密码的表单.出于这个原因,我不能使用Validators.required,因为密码字段只有在被触摸时才需要.
我的问题是,当解决输入验证时,表单仍然无效.
我做了一个plnkr来证明我的问题:http://plnkr.co/edit/obF4gC5RHkXOOlCEsIuH?p = preview
ngOnInit(): void {
this.emailField = new FormControl('mail@mail.com', Validators.email);
this.pw1 = new FormControl('', [this.passwordAreEqualValidator, Validators.minLength(2)]);
this.pw2 = new FormControl('', this.passwordAreEqualValidator);
this.pwOld = new FormControl('', this.notEmptyIfNewIsTouchedValidator);
this.form = this.formBuilder.group({
pw1: this.pw1,
pw2: this.pw2,
emailField: this.emailField,
pwOld: this.pwOld
});
}
notEmptyIfNewIsTouchedValidator(control: FormControl) : ValidationErrors | null {
if (control.dirty) {
if (control.value === '') {
return {
oldPasswordEmpty: true
}
}
const parent = control.parent,
pw1 = parent.get('pw1'),
pw2 = parent.get('pw2');
// this will trigger nothing …Run Code Online (Sandbox Code Playgroud) angular ×5
validation ×2
asp.net ×1
asynchronous ×1
boost ×1
c# ×1
c++ ×1
forms ×1
java ×1
javascript ×1
laravel ×1
laravel-5 ×1
php ×1
plugins ×1
promise ×1
testng ×1
unit-testing ×1