简体   繁体   中英

What is the proper way to validate user input?

I totally understand that JavaScript should be used to enhance a users experience, however I use it sometimes to validate the input for example to check if the password textbox is more than 5 characters or to check if the username entered in the username textbox already exists. As you can imagine if the password is less than 5 characters or the username already exists, the register button is disabled.

However, this can altered from the users browser, so is their any better way of validating the user's input?

I understand I can validate it all through the server just by checking text boxes when the register button is clicked but surely their must be better ways as such that a user cannot alter?

BTW: I'm using Visual Studio C# ASP.NET

Also, am I correct to think that regex expressions can also be altered at the clients side

Validation should be done on both the client and the server. If you choose not to use a framework that has built in validation you can definitely write your own regular expressions to do this.

Client side validation can be bypassed and its main purpose is user experience. See here . Server side validation is tougher to bypass.

Never ever depend on client side validation. There must always be double checks, one on client side and one on server side. Java script, J query and regular expression can do that for you. As a side note, USE PARAMETERISE QUERIES.

It's true that the nature of client-side code is that it is manipulatable. You can get close to preventing alteration of code through the console by using Private and Privileged members of a function. Within the constructor, privileged methods are assigned this and only call private variables. Take this example from crockford.com,

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;

    this.service = function () {
        return dec() ? that.member : null;
    };
}

The service function is priviledged and is able to call the private dec() method, which has access to the private secret variable. service is a privileged method because if directly called, it will return null.service rather than the desired value of the variable it has access to, secret .

You can use this to your advantage when evaluating passwords because server-side code can require specifically structured data that, without proper javascript, will simply not be accepted.

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