views:

33

answers:

2
<input type="file" id="css-file" />
<input type="text" id="css-url" value="eg. http://domain.com/style.css" />

I need both the fields to accept only .css files. Can I validate without having to use a validation plugin just for these 2 fields?

If anything other than .css is detected, it should give an alert()

Thanks!

A: 

Just make sure that the value matches /.css$/.

Delan Azabani
+1  A: 

You can check th extension of both with a regex or .slice() on the value, like this:

​$("form").submit(function(e) {
    $("#css-file, #css-url").each(function() {
        if(this.value.slice(-4) != ".css") {
            e.preventDefault();
            alert(this.value + " is not a .css file");
        }
    });
});​

You can give it a try here.

Nick Craver
Hmm...possible to use onChange instead?
Nimbuz
@Nimbuz - Absolutely, like this: http://jsfiddle.net/nick_craver/RVKPg/1/
Nick Craver
Great, but it still accepts the input after the alert?
Nimbuz
@Nimbuz - Correct, you can revert it if you *really* wanted to store/reverse the value...but I wouldn't from a UI standpoint. I'd put these 2 approaches together, warn on change, and don't let the form submit if it's not valid either...but I wouldn't change the input *for* the user.
Nick Craver
I just added `$(this).val('');` after the alert line, should be fine I guess. :)
Nimbuz