开发者

Why does the JQuery valid() method always return True?

开发者 https://www.devze.com 2023-01-13 22:23 出处:网络
I have a simple HTML form: <form id=\"frmNewCategory\"> <span>New Category Name:</span>

I have a simple HTML form:

<form id="frmNewCategory">
    <span>New Category Name:</span>
    <input type="text" id="txtNewCategoryName">
    <label>Amount:</label>
    <input type="text" id="txtNewCategoryAmount">
    <br>
    <input type="submit" value="Create" class="importantButton button" id="btnNewCategory">
    <input type="button" value="Cancel" class="button" id="btnCancelNewCategory">
</form>

And a bit of jQuery-driven JavaScript using the validation plugin that fires when btnNewCategory is clicked:

function onNewCategoryClick(event)
{

    $("#frmNewCategory").validate(
        {
            rules:
            {
                txtNewCategoryName : { required: true },
                txtNewCategoryAmount : {开发者_如何学C required: true, number: true }
            },
            messages:
            {
                txtNewCategoryName : { required: "*" },
                txtNewCategoryAmount: { required: "*", number: "Invalid Amount." }
            }
        });


    if (!$("#frmNewCategory").valid())
        return;

    event.preventDefault();
    var cmd = cmdFactory.createUndoableNewCategoryCommand($(this));
    cmdBus.handleCommand(cmd);  
}

The method above is supposed to validate frmNewCategory. Trouble is that even if the form has invalid values or no values at all the .valid() method still returns True.

Any ideas? What am I doing wrong?


The rules take form input "names" not "ids":

      <input type="text" name="txtNewCategoryName" />
      <input type="text" name="txtNewCategoryAmount" />


Instead of:

<input type="text" id="txtNewCategoryName">
<input type="text" id="txtNewCategoryAmount">

Use:

<input type="text" name="txtNewCategoryName">
<input type="text" name="txtNewCategoryAmount">


This pattern worked for me before:

$(".required").filter(function () { return $(this).val() == ""; }).addClass("invalidInput");

if (this.formWrp.valid() && this.formWrp.find(".invalidInput").length == 0) 
     return true;

After doing so, it seems that validation is activated.

0

精彩评论

暂无评论...
验证码 换一张
取 消