标签 submit 下的文章

bootstrap4 表单验证以ajax的方式提交 非submit表单提交


<div className="row ">
        <div className="col-sm">
          你好:)
        </div>
        <div className="col-sm">
          <div className="shadow p-3 mb-5 bg-white rounded">
          <form id="register_form" method="post" action="/api/register" >
            <div className="form-group">
              <label>Name</label>
              <input type="text" name="name" className="form-control" id="name" required onChange={(event) => SetInputRequestObj(event)}/>
            </div>
            <div className="form-group">
              <label>Email address</label>
              <input type="email" name="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="name@example.com" required onChange={(event) => SetInputRequestObj(event)}/>
              <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
            </div>
            <div className="form-group">
              <label>Password</label>
              <input type="password" name="passwd" className="form-control" id="exampleInputPassword1" required onChange={(event) => SetInputRequestObj(event)}/>
            </div>
           
            <button type="submit" className="btn btn-primary" onClick={(event) => {subForm() }}>Submit</button>
          </form>
          </div>
        </div>
        
      </div>
function subForm(){
    //阻止默认提交事件
    $("#register_form").submit(function(e){
      e.preventDefault();
    })  

    let valiRes = false; 
    //$('#register_form')是要验证的目标表单
    Array.prototype.filter.call($('#register_form'), function (target) {
      valiRes = target.checkValidity();
    }); 

    //valiRes就是表单验证的结果,返回一个bool值
    if(!valiRes)
      return;//表单验证未通过
    
    // 提交数据
    $.ajax({
      type: "post",
      url: "/api/register",
      data: JSON.stringify(RequestObj),
      contentType: "application/json;charset=utf-8",
      dataType: "json",
      success: function(data){
        
      }
    });
  }