Валидация полей формы

Алан-э-Дейл       29.03.2024 г.

Валидация первой формы

Рассматриваемый нами плагин можно использовать без внесения каких-либо заметных изменений в разметку страницы. Единственная поправка, которую вам потребуется сделать – это добавить id или class к форме, к которой нужно подключить валидацию.

Ниже приведена разметка базовой формы, ввод данных в которой мы будем проверять с помощью jQuery-плагина.

<form id="basic-form" action="" method="post">
<p>
<label for="name">Name <span>(required, at least 3 characters)</span></label>
<input id="name" name="name" minlength="3" type="text" required>
</p>
<p>
<label for="email">E-Mail <span>(required)</span></label>
<input id="email" type="email" name="email" required>
</p>
<p>
<input class="submit" type="submit" value="SUBMIT">
</p>
</form>

Для проверки введенной информации не потребуется написание дополнительного кода на JavaScript. При этом плагин обеспечит вывод сообщений об ошибках под каждым текстовым полем. У нас также будет возможность оформить сообщения в любом желаемом стиле.

Для подключения валидации к этой форме надо всего лишь вставить приведенный ниже фрагмент, написанный на JavaScript, в код страницы:

$(document).ready(function() {
$("#basic-form").validate();
});

Подразумевается, что вы уже добавили к проекту необходимые файлы плагина. Вставка приведенного выше фрагмента кода обеспечит надлежащую проверку формы и вывод сообщений об ошибках. Вот рабочая демонстрация плагина:

Сообщения об ошибках передаются в DOM (объектную модель документа) с помощью элемента label. Поскольку этот элемент предусматривает класс error, к сообщениям можно легко применить собственные стили. То же самое справедливо в отношении invalid input, у которого тоже имеется класс error.

Правила по умолчанию проверки

Нет.
правило
описание
1
Требуются: правда
Вы должны войти в поле.
2
Пульт дистанционного управления: «check.php»
Использование Ajax вызова метода check.php проверки входного значения.
3
электронная почта: верно
Вы должны ввести правильный формат электронной почты.
4
URL: правда
Вы должны ввести правильный формат URL.
5
дата: правда
Вы должны ввести правильный формат даты

IE6 проверки даты ошибки осторожность. 6
dateISO: правда
Вы должны ввести правильный формат даты (ISO), например: 2009-06-23,1998 / 01/22

Проверяется только формат, который не проверяет.
7
номер: правда
Вы должны ввести правильный номер (отрицательные числа, после десятичной точки).
8
цифры: истинные
Вы должны ввести целое число.
9
CreditCard:
Вы должны ввести действительный номер кредитной карты.
10
equalTo: «# поле»
Входные значения должны #field же.
11
принимаем:
Входная строка имеет законное расширение (загрузка файлов суффикс).
12
MaxLength: 5
Максимальная длина входной строки 5 (кандзи засчитывается как один символ).
13
MinLength: 10
Минимальная длина входной строки (символов рассчитывать как один символ) 10.
14
rangelength:
Длина входной строки должна находиться в диапазоне от 5 до 10. (кандзи количеству символов).
15
Диапазон:
Введите значение должно быть в пределах от 5 до 10.
16
макс: 5
Введите значение не более 5.
17
мин: 10
Введите значение не менее 10.

2. Example

Creating a basic form and adding validation to it.

HTML

<form action="" id='myform' method='post'>
 <table>
  <tr>
   <td>First Name</td>
   <td><input type="text" name="fname" id="fname"/></td>
  </tr>
  <tr>
   <td>Last Name</td>
   <td><input type="text" name="lname" id="lname"/></td>
  </tr>
  <tr>
   <td>Email</td>
   <td><input type="text" name="email" id="email"/></td>
  </tr>
  <tr>
   <td>Age</td>
   <td><input type="text" name="age" id="age"/></td>
  </tr>
  <tr>
   <td>Dob</td>
   <td><input type="text" name="dob" id="dob"/></td>
  </tr>
  <tr>
   <td>Password</td>
   <td><input type='password' name='password' id='password' ></td>
  </tr>
  <tr>
   <td>Retype password</td>
   <td><input type='password' name='retype_password' id="retype_password"></td>
  </tr>
  <tr>
   <td>&nbsp;</td>
   <td><input type='submit' value='Submit' ></td>
  </tr>
 </table>
</form>

CSS

form .error{
 color: red;
}

jQuery

Set the rules and messages on the input element by its names.

$(document).ready(function() {

 $("#myform").validate({
   rules: {
      fname: "required",
      lname: "required",
 
      age: {
        required: true,
        minlength: 2,
        digits: true,
        min: 18,
        max: 40 
      },
      email: {
        required: true,
        email: true,
      },
      dob:{
        date:true
      },
      password: "required",
      retype_password:{
         equalTo: "#password"
      }
   },
   messages: {
      fname: "Please enter your firstname",
      age: {
        number: 'Accept only number',
        minlength: "Atleast 2 digits"
      },
      email: "Please enter a valid email address"
   },
   submitHandler: function(form) {
      return false;
      //    form.submit();
   }
 });
});

Mark elements for validation

Unobtrusive validation is called just that (unobtrusive) because once the scripts are loaded, it’s entirely attribute-based. The form tag itself can stay as it is, but validation has to be added to every input element that needs to be validated.

Here’s how you set it up per element:

  1. Add the attribute data-val=»true» to it which enables validation on the element 
  2. Add one or more validation attributes, such as data-val-required or data-val-min. See below for a list of possible attributes

This will cause the unobtrusive validator to perform its magic, which basically consists of juggling css styles on these elements. Here’s a text input with validation:

<input type="text" name="color" data-val="true" data-val-required="Please enter a color" />

Here’s a list of the validation attributes you can use (obtained here):

  • data-val-required=»message». Shows the message when the element has no value
  • data-val-length=»message» + data-val-length-min=»min length» and/or data-val-length-max=»max length». Shows the message if the contents of the element are too long or too short
  • data-val-number=»message» or data-val-date=»message». Shows the message when the value of the element is not of the right type. Other types: data-val-creditcard, data-val-digits, data-val-email, data-val-ur 
  • data-val-regex=»message» + data-val-regex-pattern=»^pattern$». Shows the message if the value of the element does not match the pattern
  • data-val-equalto=»message» + data-val-equalto-other=»jQuery selector». Shows the message if the contents of the element are not the same as the contents of the element selected by the jQuery selector (usually «#someid»)
  • data-val-range=»message» + data-val-range-min=»min» + data-val-range-max=»max». Shows the message if the contents of the element are not in the range. Specify both min and max!

Selectors

We’ve introduced the notion of selectors without giving many details about them: A selector is a string which is used as a key to match properties in the translation files.
Take the following example:

"onlyNumber": {
    "regex": ^0-9\ +$,
    "alertText": "* Numbers only"
},
"ajaxUserCall": {
    "url": "ajaxValidateFieldUser",
    "extraData": "name=eric",
    "alertText": "* This user is already taken",
    "alertTextOk": " * User is valid",
    "alertTextLoad": "* Validating, please wait"
},
"validate2fields": {
    "alertText": "* Please input HELLO"
}

onlyNumber, onlyLetter and validate2fields are all selectors. jQuery.validationEngine comes with a standard set but you are welcome to add you own to define AJAX backend services, error messages and/or new regular expressions.

Blog of Tools

  • Accessing the Kudu REST API from Powershell
  • Reading SQL Server data from Powershell using sqlcmd
  • Linux for Windows developers
  • MOBZircles
  • Getting the Verbose switch setting in PowerShell
  • Configuring powershell remoting with network access
  • The Windows Start Menu hides duplicate shortcuts
  • Turning your Windows PC into a Wi-Fi hotspot
  • Creating a simple TypeScript web app
  • Setting up jQuery Unobtrusive Validation
  • Powershell Cheat Sheet
  • Windows Server port forwarding from the command line
  • Source code now on CodePlex
  • Composite Formatting in .NET
  • Self-closing script tags and XHTML
  • Creating a mini CMS in ASP.NET
  • Multi-Monitor vs Large-Monitor
  • QuickCode .NET 2010
  • VB6 String anomalies

The «Example.htm» File

The Example.htm file is implemented as follows:

XML
Copy Code

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
 
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=utf-8">
<title>jQuery Validation Example</title>
    <linkhref="Styles/ui-lightness/jquery-ui-1.8.13.custom.css"rel="stylesheet"type="text/css">
    <linkhref="Styles/Site.css"rel="stylesheet"type="text/css">
 
    <scriptsrc="Scripts/jquery-1.6.1.min.js"type="text/javascript"></script>
    <scriptsrc="Scripts/jquery-ui-1.8.13.custom.min.js"type="text/javascript"></script>
    <scriptsrc="Scripts/jquery.validate.min.js"type="text/javascript"></script>
    <scriptsrc="Scripts/jquery.validate.wrapper.js"type="text/javascript"></script>
 
<scripttype="text/javascript"language="javascript">
 
    $(document).ready(function () {
        // 1. prepare the validation rules and messages.
        var rules = {
            textbox1: {
                required: true,
                minlength: 2
            },
            textbox2: "required",
            textbox3: "required"
        };
        var messages = {
            textbox1: {
                required: "textbox1 is required",
                minlength: "textbox1 needs to be at least length 2"
            },
            textbox2: "textbox2 is requried",
            textbox3: "textbox3 is required"
        };
 
        // 2. Initiate the validator
        var validator
            = new jQueryValidatorWrapper("FormToValidate",
                rules, messages);
 
        // 3. Set the click event to do the validation
        $("#btnValidate").click(function () {
            if (!validator.validate())
                return;
 
            alert("Validation Success!");
        });
    });
       
</script>
</head>
 
<body>
 
<formid="FormToValidate"action="#">
<table>
    <tr>
        <td>
            <inputtype="text"id="textbox1"name="textbox1">
        </td>
        <td>
            <inputtype="text"id="textbox2"name="textbox2">
        </td>
    </tr>
    <tr>
        <td>
            <inputtype="text"id="textbox3"name="textbox3">
        </td>
        <td>
            <inputtype="button"id="btnValidate"style="width: 100%"value="Validate">
        </td>
    </tr>
</table>
</form>
 
</body>
</html>

This HTML file has three text boxes and a button. The purpose of this example is to validate the content in the text boxes when the button is clicked. To set up the validation, we need to go through three steps in the event.

  • Prepare the validation rules and the messages to show if the validation fails.
  • Create a validator object by passing the ID of the HTMl Form that contains the text boxes to the function. The validation rules and messages are also passed to this function. The function is implemented in the jquery.validate.wrapper.js file.
  • Hook up the click event for the button to start validation.

This piece of code is pretty simple, but you should pay some attention to the following:

  • All the required JavaScript files and style sheets need to be referenced properly.
  • All the text boxes need to have a «» attribute. The validation rules and messages are associated with the attribute.
  • All the text boxes to be validated need to be in the HTML Form that is used to create the validator object.

Now let us take a look at the function.

The jQuery Validation Wrapper

The function is implemented in the jquery.validate.wrapper.js file:

JavaScript
Copy Code

var dialogIdSeed = 1000000000;
function jQueryValidatorWrapper(formId, rules, messages) {
    
    
    var dialogId = "V_dia_log" + dialogIdSeed++;
    while ($("#" + dialogId).length != ) {
        alert(dialogId);
        dialogId = "V_dia_log" + dialogIdSeed++;
    }
 
    
    
    var dialogText = "<div id='" + dialogId
            + "' title='Please correct the errors ...'>"
            + "<ul /></div>";
    $("body").append(dialogText);
    var $dialog = $("#" + dialogId);
    var $ul = $("#" + dialogId + ">ul");
 
    $dialog.dialog({
        autoOpen: false,
        modal: true,
        close: function (event, ui) {
            $ul.html("");
        }
    });
 
    
    var showErrorMessage = false;
    var validator = $("#" + formId).validate({
        onchange: true,
        rules: rules,
        messages: messages,
        errorPlacement: function (error, element) {
            if (showErrorMessage) {
                var li = document.createElement("li")
                li.appendChild(document
                    .createTextNode(error.html()));
                $ul.append(li);
            }
        },
        showErrors: function (errorMap, errorList) {
            this.defaultShowErrors();
            if ((errorList.length != ) && showErrorMessage) {
                $dialog.dialog('open');
            }
        }
    });
 
    
    this.validate = function () {
        showErrorMessage = true;
        var result = validator.form();
        showErrorMessage = false;
 
        return result;
    };
}

The function does the following:

  • It first creates a element and appends it to the DOM. It makes sure that the ID of the element is unique in the web page. This element will be used as a dialog box to display the error messages if the validation fails.
  • It hooks up the validation rules and messages with the HTML Form that will be validated using the jQuery Validation Plug-in.
  • At last, it creates a function that starts the validation.

Set Default String Length

Locate the file “app/Providers/AppServiceProvider”, and add following line of code to the top of the file

use Illuminate\Support\Facades\Schema;

1 useIlluminate\Support\Facades\Schema;

and inside the boot method set a default string length as given below –

Schema::defaultStringLength(191);

1 Schema::defaultStringLength(191);

So this is how “app/Providers/AppServiceProvider” file looks like –

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
public function boot() {
Schema::defaultStringLength(191);
}
public function register(){
}
}

1
2
3
4
5
6
7
8
9
10
11
12

<?php

namespaceApp\Providers;

useIlluminate\Support\ServiceProvider;

useIlluminate\Support\Facades\Schema;

classAppServiceProviderextendsServiceProvider

{

publicfunctionboot(){

Schema::defaultStringLength(191);

}

publicfunctionregister(){

}

}

Create Laravel Controller

Next, we have to create a controller to display contact form and to handle form validation and submit operations. Lets Create a controller named ContactController using command given below

php artisan make:controller ajaxFormSubmitValidation/ContactController

1 php artisan makecontroller ajaxFormSubmitValidationContactController

Once the above command executed, it will create a controller file ContactController.php in app/Http/Controllers/ajaxFormSubmitValidation directory.

Open the ajaxFormSubmitValidation/ContactController.php file and put the following code in it.

app/Http/Controllers/ajaxFormSubmitValidation/ContactController.php

<?php

namespace App\Http\Controllers\ajaxFormSubmitValidation;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Contact;
use Validator,Redirect,Response;

class ContactController extends Controller
{
//
public function index()
{
return view(‘ajaxFormSubmitValidation.contact_form’);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

<?php

namespaceApp\Http\Controllers\ajaxFormSubmitValidation;

useIlluminate\Http\Request;

useApp\Http\Controllers\Controller;

useApp\Contact;

useValidator,Redirect,Response;

classContactControllerextendsController

{

//

publicfunctionindex()

{

returnview(‘ajaxFormSubmitValidation.contact_form’);

}

publicfunctionstore(Request$request)

{

request()->validate(

‘name’=>’required’,

’email’=>’required|email’,

‘phone’=>’required’

);

$data=$request->all();

$result=Contact::insert($data);

$arr=array(‘msg’=>’Something went wrong. Please try again!’,’status’=>false);

if($result){

$arr=array(‘msg’=>’Contact Added Successfully!’,’status’=>true);

}

returnResponse()->json($arr);

}

}

In this controller, we have following methods –

index() :- To display contact form.

store() :- To validate and submit form data,

Develop functions that show the error / success

The following function highlights the border of the input field and displays an error message if the input field is invalid:

How it works.

First, get the parent element of the input field, which is the element that contains the class:

Second, remove the class and add the class to the element:

Third, select the element inside the element:

Notice that you use the instead of the .

Finally, set the error message to its property of the element:

The function that shows the success indicator is similar to the function:

Unlike the function, the function removes the class, adds the class, and set the error message to blank.

Now, you can use the utility function above to check for each field.

Создание собственных сообщений об ошибках

Рассматриваемый нами плагин позволяет создавать собственный набор сообщений об ошибках, соответствующих различным правилам проверки данных, введенных в форму. Создание сообщения об ошибке начинается с задания объекта-значения для ключа messages. Для каждого поля ввода определяется такая пара ключа и значения, и соответствующее сообщение об ошибке.

Ниже приведен пример кода, который обеспечивает вывод сообщений об ошибках при вводе неверных данных в любое из полей формы:

messages : {
name: {
minlength: "Name should be at least 3 characters"
},
age: {
required: "Please enter your age",
number: "Please enter your age as a numerical value",
min: "You must be at least 18 years old"
},
email: {
email: "The email should be in the format: abc@domain.tld"
},
weight: {
required: "People with age over 50 have to enter their weight",
number: "Please enter your weight as a numerical value"
}
}

Как и правила, messages опираются на названия полей ввода. Каждое из этих полей принимает объект, состоящий из ключа и значения. Ключом является правило валидации, а значением – сообщение об ошибке, которое выводится в случае нарушения правила.

Например, поле age с помощью свойства required вызовет сообщение об ошибке, если останется незаполненным. Кроме того, если введенная информация не является числовым значением, поле вызовет ошибку number.

Как вы сможете убедиться, плагин отображает сообщения об ошибках, используемые по умолчанию в том случае, если вы не предоставили ему свои собственные. Попробуйте ввести различные данные в приведенный ниже демонстрационный образец, и вы увидите как стандартные, так и кастомные уведомления об ошибках.

Usage

You take any form you like, spice it up with new HTML5 input types
and attributes and make a single call to jQuery
Tools validator. Here is the HTML layout for the
example form above:

<form id="myform"><fieldset><h3>Sample registration form</h3><p> Enter bad values and then press the submit button. </p> <p><label>email *</label><input type="email" name="email" required="required" /></p><p><label>website *</label><input type="url" name="url" required="required" /></p><p><label>name *</label><input type="text" name="name" pattern="{5,}" maxlength="30" /></p><p><label>age</label><input type="number" name="age" size="4" min="5" max="50" /></p><p id="terms"><label>I accept the terms</label><input type="checkbox" required="required" /></p><button type="submit">Submit form</button><button type="reset">Reset</button></fieldset></form>

HTML

And here is the validator call that enables form
validation:

$("#myform").validator();

JavaScript

When the form is submitted the validator will make sure that the
input fields pass all the rules that are defined for them. If there
are any errors an error message appears above all failed
fields. When the user starts fixing the values each error message
will magically disappear once the input is valid. Look at
the minimal
setup for more details.

Validating inputs without a form

The tool validates all input fields except buttons and hidden fields
inside a particular form. You can also select particular fields and
validate them. For example:

  // initialize validator for a bunch of input fieldsvar inputs = $("#mydiv :input").validator(); // perform validation programmaticallyinputs.data("validator").checkValidity();

JavaScript

Since v1.2.3 another $(«…»).validator() call
would the existing instance and will install
a completely new validator instance.

Примеры Demo

Вымышленные примеры

  • Контейнер Сообщение об ошибке
  • Собственное сообщение в качестве элемента данных
  • (Вниз падение ящика) радио (радио — кнопки), флажок (кнопка проверки) и выберите
  • Интерактивная форма (форма) и плагин (представление AJAX)
  • Методы Пользовательские и отображение сообщений
  • Динамические формы
  • Использование JQuery UI ThemeRoller пользовательский стиль формы
  • TinyMCE — легкий браузер на основе визуальный редактор
  • поле ввода файла
  • JQuery Mobile аутентификации с помощью форм

Примеры реального мира

  • Регистрационная форма молока
  • Форма регистрации Marketo
  • продажа Жилищное складной панель
  • Remote CAPTCHA на основе (PIN — код) проверка

Использование встроенных проверок

Подключаемый модуль Validation поддерживает большое количество встроенных проверок данных, введенных в полях формы. С одним из них (min) вы уже познакомились в предыдущем примере. Полный список встроенных проверок представлен в таблице ниже:

Встроенные проверки, предусмотренные в модуле Validation
Проверка Описание
creditcard: true Значение должно содержать номер кредитной карты
date: true Значение должно быть действительной датой JavaScript
digits: true Значение должно содержать лишь цифры
email: true Значение должно быть действительным адресом электронной почты
max: maxVal Значение не должно превышать maxVal
maxlength: length Значение должно содержать не более length символов
min: minVal Значение не должно быть меньше minVal
minlength: length Значение должно содержать не менее length символов
number: true Значение должно быть десятичным числом
range: Значение должно находиться в пределах указанного диапазона
rangelength: Значение должно содержать не менее minLen и не более maxLen символов
required: true Значение обязательно должно быть указано
url: true Значение должно быть URL-адресом

Несколько правил могут быть объединены в одно. Тем самым обеспечиваются компактность и наглядность кода, осуществляющего проверку. Эти правила могут применяться к элементам несколькими способами. Все они описаны в следующих разделах.

Применение правил проверки на основании принадлежности классам

Чаще всего я пользуюсь методикой, в которой применение правил проверки основывается на классах элементов. Именно такой подход предпринят в данном примере. Однако ничто не заставляет вас ограничиться только одним видом проверки. Для проверки различных аспектов значения, предоставленного пользователем, можно объединить в одном правиле несколько видов проверки, как показано в примере ниже:

В этом примере проверки required, digits, min и max объединены в одно правило, позволяющее убедиться в том, что предоставленное пользователем значение является обязательным для ввода, включает только цифры и находится в интервале от 0 до 100.

Обратите внимание на то, что для связывания правила с классом используется метод addClassRules(). Аргументами этого метода являются один или несколько наборов проверок и имя класса, к которому они применяются

Как видно из примера, метод addClassRules() вызывается для свойства validator основной функции jQuery $().

Доступ к каждому проверяемому элементу формы осуществляется индивидуально, а это означает, что диагностические сообщения, выводимые для пользователя, будут разными, в зависимости от характера возникшей проблемы, как показано на рисунке:

Здесь введено несколько значений, каждое из которых не проходит одного из видов проверки

Важно отметить, что проверки выполняются в том порядке, в каком они определены в правиле. Если вы посмотрите на сообщение для продукта «Пион», то увидите, что оно не прошло проверку digits

Изменив порядок определения проверок, вы получите другое сообщение.

Применение правил проверки непосредственно к элементам

Следующая методика позволяет применять правила к определенным элементам, как показано в примере ниже:

Обратите внимание: мы вызываем метод, определяющий правила, для объекта jQuery и передаем ему строку add и объект отображения данных с видами проверок, которые хотим выполнить, и их аргументами. Метод rules() воздействует лишь на первый элемент выбранного набора, и поэтому для расширения сферы его действия мы должны использовать метод each()

В данном случае выбираются все элементы input, являющиеся потомками элемента row1, к которым и применяются указанные проверки.

При вызове метода rules() можно добавлять и удалять отдельные проверки, используя соответственно методы add() и remove().

Правила, применяемые к элементам с использованием методов rules(), интерпретируются до того, как будут интерпретироваться правила, применяемые с использованием классов. В контексте нашего примера это означает, что элементы верхнего ряда будут проверяться с использованием значения min, равного 10, и значения max, равного 20, в то время как к другим элементам input будут применяться соответственно значения 0 и 100. Результат представлен на рисунке:

Getting Into jQuery Validation

<script type="text/javascript">
$(document).ready(function()
{ 
     $('#button-save).click(function() 
{  
        var emailAddressValue = $("#textboxEmailAddress").val();
        if(emailAddressValue == '') {
$("#textboxEmailAddress ").after('<span class="error">Please specify an email address.</span>');
return false;
        	}
 
    });
});
</script>

The .val() method is used to retrieve the values from the form object. It returns single/multiple values depending on the form object that is used. The after() method instructs to insert the specified html after the object that the select expression retrieves.

jQuery supports a Full-Featured and flexible Validation plug-in that lets you easily hook it to ASP.Net applications. . The jQuery validation plugin leverages a CSS selector like syntax to apply a set of validation rules. You can download the plugin (js) file from jQuery website.

Refer it in your web application with the script tag as follows:

<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready( function() {
               $("#formName").validate({
                           rules:{
                                           username:{
                                                               required:true,
                                                               minlength:10
                                           },
                                           password:{
                                                               required:true,
                                                               minLength:5
                                           },
                                           confirm_password:{
                                                               required:true,
                                                               minlength:5,
                                                               equalTo:"#password"
                                           },
                                           email:{
                                                               required:true,
                                                               email:true
                                           },
},
                            messages:{
                                           username:{
                                                         required: “Please specify a username",
                                                         minLength:"The username is too short"
                                           },
                                           password:{
                                                          required:"Please specify a password"
                                           minLength:"The password is too short"
                                           },
                                           confirm_password:{
                                                  required:"Please provide a password",
                                                  minLength:"The password is too short",
                                                  equalTo: "Please specify the same password as above"
                                           },
                                           email: "This is not a valid email address.",
                                                       }
               });
        }
</script>

The password and confirm password objects are matched by the validation plugin for you and shows the message on the equalTo attribute if they don’t match. The validation logic seems to be unified and totally configurable at one place.

For your ASP.Net objects, you can set the validation CSS classes that will trigger the validations, like below. The class data offers the metadata for the library to validate the data for you.

<input type="text" name="nameoftheTextBox" id="idofTheTextBox" class="required email" />

The messages that appear as errors are in English and there are translations also available in many other locales. From MSDN, “To support validation for non-English locales in ASP.NET MVC 3 applications, you must include a locale-specific jQuery methods script file for each language you support.” You can download these scripts here.

For example, for German locales, use the following file from the URL listed previously:

jquery.validate_17jquery-validatelocalizationmethods_de.js”

You can also use dynamically add the rules to an object. jQuery lets you query using “class” names, like in the following example, and lets you control the missing input.

<script type="text/javascript">
$(document).ready(function() {
$("#formname").validate();
});

$('.email).rules('add', { 
        required: true, 
        messages: { 
            required: Please share your email-id.' 
        } 
    });
});
</script>

<input name="textboxEmailAddress" type="text" id="textboxEmailAddressId" class=" email” />

Note that the last two code samples (shown above) indicate that whenever the form is submitted through any control, the validation would happen. You do not want this to happen, especially when you have multiple submit buttons on a single form. So the best way is to trigger the Validate functions from the button click events, like this:

$("#submitButton").click(function() {
  return $("# formname ").valid();
});

Note that you should also disable the form submit in the form validate function like below:

$(document).ready(function() {
$("#formname").validate({onsubmit: false});
});

ASP.Net MVC supports the client side validation using the Model validation that is specified through the Object attributes in the Model. If you want to replace the client-side validations with jQuery , all you have to do is:

a) Refer the jQuery validate and the MicrosoftMvcJQueryValidation JavaScript files.
b) And add the “Html.EnableclientValidation()” code in the view. 

There are more beautiful validation workflows that can be implemented using jQuery. Here are few from my bookmarks:

  • Combining JQuery Form Validation and Ajax Submission with ASP.NET
  • Remote validation using Ajax endpoint for MVC

But do remember that you have to continue to do server-side validation to ensure that you ASP.Net applications are foolproof.

Build the HTML form

First, open the file and enter the following code:

In this HTML file, we place the file in the section and file in the body section before the closing tag.

Second, add the following HTML markup to create the signup form. The final index.html file will look like the following:

The notable thing about the signup form is that each field is wrapped in a with the class .

Each form field has three elements:

  • A label
  • An input field
  • A element

You’ll use the tag to show the error message to the users.

If an input field isn’t valid, we’ll make its border color red by adding the class to the element. It’ll look like this:

If the value of an input field is valid, then we’ll make its border color green by adding the class to the element as follows:

Check out the style.css for details of the and classes.

Develop input field validating functions

You’ll develop four functions for validating values of the form fields:

1) Validate the username field

The following function uses:

  • The function to check if the username is provided.
  • The function to check if the length of the username is between 3 and 25 characters.
  • The and functions to show the error and success indicator.

The function returns if the field passes the checks.

2) Validate the email field

3) Validate the password field

The following function checks the password field if it is provided and match the required format:

4) Validate the confirm password field

The function checks if the confirm password is the same as the password.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.