Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery, how to know when input have a :invalid selector?

I have this code:

HTML

<input type="text" data-value="1" data-type="input-records" placeholder="Value" pattern="\d{1,4}$" />

CSS

input[type=text]:invalid { background-color: red; }

Javascript

$("[data-type=input-records]").die().live("keypress", function (e) {
    if (!($(this).val().length + 1) < 5) {
        e.preventDefault();
        return;
    }

    // More code below...
});

I want to make a validation like this:

if (!$(this).hasSelector(":invalid")) {
    showMessage("Invalid value");
}
like image 552
Sergio Flores Avatar asked Jan 17 '13 17:01

Sergio Flores


People also ask

Which of the selector is invalid?

The invalid selector error is a WebDriver error that occurs when an element retrieval command is used with an unknown web element selector strategy. The available selector strategies are CSS, link text, partial link text, tag name, and XPath. Any other selector strategy is rejected with this error.

How to validate input type in jQuery?

jQuery(document). ready(function() { jQuery("#forms). validate({ rules: { firstname: 'required', lastname: 'required', u_email: { required: true, email: true,//add an email rule that will ensure the value entered is valid email id. maxlength: 255, }, } }); });

How can check input value or not in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.

What is invalid Css?

The :invalid selector allows you to select <input> elements that do not contain valid content, as determined by its type attribute. :invalid is defined in the CSS Selectors Level 3 spec as a “validity pseudo-selector”, meaning it is used to style interactive elements based on an evaluation of user input.


1 Answers

Use the is function to test for the :invalid pseudoclass:

if ($(this).is(":invalid")) {
    showMessage("Invalid value");
}

Example: http://jsbin.com/ikuwur/2/edit

like image 181
Andrew Whitaker Avatar answered Oct 16 '22 10:10

Andrew Whitaker