Ответ 1
Примечание. Это пример для angular 1.2.0-rc.3. Вещи могут вести себя по-другому в других версиях
Как и другие, было заявлено, что немного сложно отключить проверку входных параметров по умолчанию. Вам нужно добавить свою собственную директиву в элемент ввода и обработать вещи там. Ответ Сергея правильный, однако он представляет некоторые проблемы, если вам нужно несколько валидаторов на элементе и не хотите, чтобы встроенный валидатор срабатывал.
Вот пример проверки поля электронной почты с добавленным обязательным валидатором. Я добавил комментарии к коду, чтобы объяснить, что происходит.
Элемент ввода
<input type="email" required>
Директива
angular.module('myValidations', [])
.directive('input', function () {
var self = {
// we use ?ngModel since not all input elements
// specify a model, e.g. type="submit"
require: '?ngModel'
// we need to set the priority higher than the base 0, otherwise the
// built in directive will still be applied
, priority: 1
// restrict this directive to elements
, restrict: 'E'
, link: function (scope, element, attrs, controller) {
// as stated above, a controller may not be present
if (controller) {
// in this case we only want to override the email validation
if (attrs.type === 'email') {
// clear this elements $parsers and $formatters
// NOTE: this will disable *ALL* previously set parsers
// and validators for this element. Beware!
controller.$parsers = [];
controller.$formatters = [];
// this function handles the actual validation
// see angular docs on how to write custom validators
// http://docs.angularjs.org/guide/forms
//
// in this example we are not going to actually validate an email
// properly since the regex can be damn long, so apply your own rules
var validateEmail = function (value) {
console.log("Validating as email", value);
if (controller.$isEmpty(value) || /@/.test(value)) {
controller.$setValidity('email', true);
return value;
} else {
controller.$setValidity('email', false);
return undefined;
}
};
// add the validator to the $parsers and $formatters
controller.$parsers.push(validateEmail);
controller.$formatters.push(validateEmail);
}
}
}
};
return self;
})
// define our required directive. It is a pretty standard
// validation directive with the exception of it priority.
// a similar approach must be take with all validation directives
// you would want to use alongside our `input` directive
.directive('required', function () {
var self = {
// required should always be applied to a model element
require: 'ngModel'
, restrict: 'A'
// The priority needs to be higher than the `input` directive
// above, or it will be removed when that directive is run
, priority: 2
, link: function (scope, element, attrs, controller) {
var validateRequired = function (value) {
if (value) {
// it is valid
controller.$setValidity('required', true);
return value;
} else {
// it is invalid, return undefined (no model update)
controller.$setValidity('required', false);
return undefined;
}
};
controller.$parsers.push(validateRequired);
}
};
return self;
})
;
Там у вас есть. Теперь вы контролируете входные проверки type="email"
. Пожалуйста, используйте правильное регулярное выражение, чтобы проверить электронную почту, хотя.
Следует отметить, что в этом примере validateEmail
выполняется до validateRequired
. Если вам нужно validateRequired
выполнить перед любыми другими проверками, просто добавьте его в массив $parsers
(используя unshift
вместо push
).