Search code examples
javascriptjqueryhtmlknockout.jsknockout-mvc

how to bind input type= 'email' in knockoutjs


I am using KnockoutJS with MVC.

I want to know whether the emailId is valid or invalid and based on it i have to enable/disable button and set error title for textbox.

here is my .cshtml

<div class="nmc-righttab" style="width:265px;">
    <input class="nmc-text" type="email" maxlength="50" id="txtEmail" data-bind="value: emailAddress, valueUpdate: 'input'",css: { faultyBrush: (checkValidEmail() },attr: {title: InvalidEmailTitle } style="width:245px;" />
 </div> 

 <input type="submit" class="btn nmc-button" data-bind="click: searchUsers,enable: canSearchUsers,css: { 'btn-primary': (canSearchUsers() == true) }" id="searchUser" value="@Res.CommonStrings.Search" />

here is my JS Code:

 this.emailAddress = ko.observable('');
 this.invalidEmailTitle = ko.observable('');
 this.canSearchUsers = ko.computed(function () {
     try {
         if (this.emailAddress().trim().length!==0)
             return true;
         else
              return false;
     } catch (error) {
         NMCApp.showNMCExceptionWindow('Jquery Error:' + error);
     }
}, this);

this.checkValidEmail(input) {

}

Please let me know How to know the validity of the email type textbox and how can i change the title for the same in case of invalid in Knockout JS.

how can I get the validity of textbox with input type "email"


Solution

  • If you don't want to use the Validation plugin, you can test the input against your own regex:

    HTML

    <input data-bind="textInput: emailAddress, css: { 'faultyBrush': !checkValidEmail()}" class="nmc-text" type="email" maxlength="50" id="txtEmail" />
    

    JS

    var self = this;
    self.emailAddress = ko.observable('');
    self.checkValidEmail = ko.pureComputed(function () {
        if (!self.emailAddress()) return false;
        var pattern = /REGEX-GOES-HERE/i;
        return pattern.test(self.emailAddress());
    });
    

    There are a couple of patterns here.