JQuery验证在保存按钮单击处理程序中不起作用

时间:2017-12-25 03:59:20

标签: javascript jquery html validation

我已经尝试了几个小时来进行验证工作,但无济于事。我在input元素中包含了name属性。脚本来源也包括在内。验证方法也被触发了。内容未经过验证。任何人都可以看到我的代码有什么问题吗?提前致谢。 Merry X'mas!

我的Html代码

<input type="text" id="sessionSynopsisNameInput" name="sessionSynopsisNameInput" 
  class="form-control input-group-lg" maxlength="70" placeholder="Session Name" value=""/>
<div class="errMsg"></div>

我的Javascript代码

setupFormValidationRules();
function setupFormValidationRules() {
    jQuery.validator.addMethod('lettersonly', function (value, element) {
        return this.optional(element) || /^[a-zA-Z ]*$/.test(value);
    });

    $('#dataForm').validate({
        rules: {
            sessionSynopsisNameInput: {
                required: true,
                lettersonly: true
            }
        },
        messages: {
            sessionSynopsisNameInput: {
                required: 'Please enter Session Synopsis Name',
                lettersonly: 'Only spaces and alphabets are allowed'
            }
        }
    });
}

在save按钮单击处理程序中调用validate方法。

$('#saveButton').on('click', function () {
    $('#dataForm').validate();
});

这些是我收录的脚本来源

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>

1 个答案:

答案 0 :(得分:0)

lettersonly 已经存在其他方法我必须更改名称 lettersonly1 并且它可以正常工作例子

&#13;
&#13;
AppService.class

    public class AppService extends Service {
    private MyThread thread;
    PowerManager.WakeLock wl;
    double latitude; 
    double longitude; 

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        thread = new MyThread();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!thread.isAlive()) {      
            thread.start();
        }
        return START_STICKY;   
    }

    private class MyThread extends Thread {  
        private static final String tag = "Sevice Demo";
        private static final int delay = 300000;
        private int roundNumber = 0;
        private boolean finishService = false;

        @Override
        public void run() {
            while (true) {
                PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
                        getApplicationContext().POWER_SERVICE);
                wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
                wl.acquire();
                wl.release();

                GPSTracker gps = new GPSTracker(AppService.this);
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();
                Log.d("dddd",String.valueOf(latitude)+" & "+String.valueOf(longitude));

                try {
                    sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (finishService) {
                    return;
                }
            }
        }
    }

    @Override
    public void onDestroy() {  
        Toast.makeText(this, "Service Stop...", Toast.LENGTH_LONG).show();
        if (thread.isAlive()) {     
            stopService(new Intent(this, AppService.class));
        }
        super.onDestroy();
    }

    public class GPSTracker extends Service implements LocationListener {
        private final Context mContext;
        boolean isGPSEnabled = false;          
        boolean isNetworkEnabled = false;     
        boolean canGetLocation = false;    
        Location locations;

        private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
        private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 
        protected LocationManager locationManager;         

        public GPSTracker(Context context) {
            this.mContext = context;
            getLocation();
        }

        public Location getLocation() {
            try {
                locationManager = (LocationManager) mContext
                        .getSystemService(LOCATION_SERVICE);

                // get GPS status
                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                // get network status
                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (!isGPSEnabled && !isNetworkEnabled) {
                    // no network provider is enabled
                } else {
                    this.canGetLocation = true;
                    if (isNetworkEnabled) {
                        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            //return TODO;
                        }
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                    }
                    if (locationManager != null) {
                        locations = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    }
                    if (locations != null) {
                        latitude = locations.getLatitude();
                        longitude = locations.getLongitude();
                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (locations == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            locations = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (locations != null) {
                                latitude = locations.getLatitude();
                                longitude = locations.getLongitude();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return locations;
        }

        public double getLatitude() {
            if (locations != null) {
                latitude = locations.getLatitude();
            }
            return latitude;
        }

        public double getLongitude() {
            if (locations != null) {
                longitude = locations.getLongitude();
            }
            return longitude;
        }

        public boolean canGetLocation() {
            return this.canGetLocation;
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onLocationChanged(Location location) {

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }

}
&#13;
setupFormValidationRules();

function setupFormValidationRules() {      
    $.validator.addMethod('lettersonly1', function (value, element) {
        return this.optional(element) || /^[^-\s][a-zA-Z\s-]+$/.test(value);
    });

    $('#dataForm').validate({
        rules: {
            sessionSynopsisNameInput: {
                required: true,
                lettersonly1: true
            }
        },
        messages: {
            sessionSynopsisNameInput: {
                required: 'Please enter Session Synopsis Name',
                lettersonly1: 'Only spaces and alphabets are allowed'
            }
        }
    });
}

$(function(){
    $('#dataForm').validate()
})

$("#dataForm").on("submit", function(){
    if($(this).valid()){
        console.log('submit');
        $(this).submit();
    }
    
    return false;
})
&#13;
&#13;
&#13;