简体   繁体   中英

Change border color on textarea validation

Need to make a custom error effect on validation of textarea . Tries to do it with little script, which changes errorClass , maybe I'm doing something wrong or misunderstood.

$('#message').validate({ errorClass:'error'});

Error should look like that: http://i.imgur.com/3lnnX8S.png

By now it looks default: http://i.imgur.com/U71paPi.png

There is that I've got: JSFiddle

As I can see from your example, you're using html5 validation. To style those use the following pseudo selector :

input:focus:invalid, textarea:focus:invalid{
    border-color: red !important;
    -webkit-box-shadow: inset 0 1px 1px red;
    box-shadow: inset 0 1px 1px red;
}

:focus is necessary for when you ONLY want to validate when user is typing.

Check your updated example here: https://jsfiddle.net/2436ey01/

For adding custom messages you can customize the built in validation using javascript:

var message = document.querySelector('textarea#message');

message.oninvalid = function(e) {
    e.target.setCustomValidity("");
    if (!e.target.validity.valid) {
        e.target.setCustomValidity("You shall not pass!");
    }
};

Here an example: https://jsfiddle.net/z73gtr6s/

I think this might help you. As i do not know what library you using, still can help you with some way.

JS/JQuery Code

$('.submit').click(function(){
    var content = $('textarea').text();
    if(content == "")
    {
        $('textarea').addClass('redBorder');
    }
    else
    {
        $('textarea').removeClass('redBorder');
    }
});

Working:Fiddle

If you want a good (easy to use) library to add inline error messages- You can use webshim , working fiddle for your example (without css)

js:

webshim.setOptions('forms', {
    lazyCustomMessages: true
});

//start polyfilling
webshim.polyfill('forms');

I used the inline validation as seen here:

http://afarkas.github.io/webshim/demos/demos/forms.html#UI-replaceValidationUI

Seems there are a couple of issues:

  1. You don't have an .error class defined in your CSS - which might be something like #message.error and have the border: 1px solid red or what ever.

  2. Looks like there is an error in the console that comes through as validates is not a function, meaning that you have wrong dependencies so check to see what libraries you need.

.touch #message:focus {
box-shadow: none;
border-color: #383838; 
}

comment this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM